/*
 * This file is part of LangMan.
 *
 * LangMan is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * LangMan is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with LangMan.  If not, see <http://www.gnu.org/licenses/>.
 */

package langman.util.guifactory;

import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import langman.util.doping.Context;
import langman.util.doping.Inject;
import langman.util.doping.SingletonBean;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;

@SingletonBean
public class BeanFXMLLoader {
    private final Context context;

    @Inject
    public BeanFXMLLoader(Context context) {
        this.context = context;
    }

    public <T extends FXMLBeanControl> T load(String url, Class<T> controllerClass) throws IOException {
        try (InputStream fxmlStream = controllerClass.getResourceAsStream(url)) {

            if (fxmlStream == null) {
                throw new IOException("Couldn't find FXML file for class " + controllerClass);
            }

            T controllerInstance = FXMLBeanControl.class.isAssignableFrom(controllerClass) ?
                    context.getBean(controllerClass) :
                    controllerClass.getConstructor().newInstance();

            FXMLLoader loader = new FXMLLoader();
            loader.setController(controllerInstance);
            Node loadedNode = (Node) loader.load(fxmlStream);

            controllerInstance.setNode(loadedNode);

            return controllerInstance;
        } catch (InvocationTargetException | IllegalAccessException | InstantiationException | NoSuchMethodException e) {
            throw new IOException(e);
        }
    }
}